package com.point.common.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;


@Slf4j
public class DateUtil {

    public static RangeOfMonth getRangeOfMonth(Date date) {
        if (date != null) {
            DateTime dateTime = new DateTime(date.getTime());
            int year = dateTime.getYear();
            int month = dateTime.getMonthOfYear();
            Date start = parse("yyyy-MM", String.format("%d-%02d", year, month));
            Date end = new DateTime(start.getTime()).plusMonths(1).toDate();
            return new RangeOfMonth(start, end);

        }
        return null;
    }

    /**
     * 月格式数据 比如  2019-01
     *
     * @param date
     * @return
     */
    public static RangeOfMonth getRangeOfMonth(String date) {
        return getRangeOfMonth(parse("yyyy-MM", date));
    }

    /**
     * @param date
     * @return
     */
    public static Date parse(String pattern, String date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        try {
            Date formatDate = dateFormat.parse(date);
            return formatDate;
        } catch (Exception ex) {
            log.info("日期格式化错误", ex);
        }
        return null;
    }

    public static String format(String pattern, Date date) {
        assert pattern != null && date != null;
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        try {
            return dateFormat.format(date);
        } catch (Exception ex) {
            log.info("日期格式化错误", ex);
        }
        return null;
    }


    public static String localDateTimeFormat(String pattern, LocalDateTime localDateTime) {
        if (StringUtils.isBlank(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }


    @Data
    public static class RangeOfMonth {
        Date begin;
        Date end;

        public RangeOfMonth(Date begin, Date end) {
            this.begin = begin;
            this.end = end;
        }
    }
}
